package com.ruoyi.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Source;

import cn.hutool.core.util.IdUtil;
import com.alibaba.excel.EasyExcel;
import com.ruoyi.Listener.DailyImportListener;
import com.ruoyi.domain.Dictionary;
import com.ruoyi.domain.ProductionInfo;
import com.ruoyi.domain.RawmaterialInfo;
import com.ruoyi.service.DictionaryService;
import com.ruoyi.service.IProductionInfoService;
import com.ruoyi.service.RawmaterialInfoService;
import com.ruoyi.utils.EasyExcelConfig;
import com.ruoyi.utils.ExcelFillCellMergeStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 加工成品信息Controller
 *
 * @author ruoyi
 * @date 2024-02-28
 */
@RestController
@RequestMapping("/proinfo")
public class ProductionInfoController extends BaseController {
    @Autowired
    private IProductionInfoService productionInfoService;

    @Autowired
    private RawmaterialInfoService rawmaterialInfoService;

    @Autowired
    private DictionaryService dictionaryService;

    /**
     * 查询加工成品信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(ProductionInfo productionInfo) {
        startPage();
        if (productionInfo.getShelf() != null) {
            productionInfo.setShelf(productionInfo.getShelf() + "个月");
        }

        List<ProductionInfo> list = productionInfoService.selectProductionInfoList(productionInfo);
        return getDataTable(list);
    }

    /**
     * 导出加工成品信息列表
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, ProductionInfo productionInfo) throws IOException {
        Integer pageSize = 5000;
        List<ProductionInfo> list = productionInfoService.selectProductionInfoList(productionInfo);


//通过计算得出需要sheet的个数
        int sheetNum = list.size() % pageSize == 0 ? list.size() / pageSize : list.size() / pageSize + 1;
        List<ProductionInfo> productionInfos;
        for (int i = 1; i <= sheetNum; i++) {
            if (i * pageSize - 1 <= list.size()) {
                productionInfos = list.subList((i - 1) * pageSize, i * pageSize - 1);
            } else {
                productionInfos = list.subList((i - 1) * pageSize, list.size());

            }


            response.setContentType(EasyExcelConfig.RESPONSE_TYPE);
            response.setCharacterEncoding(EasyExcelConfig.CHARSET);

            //合并单元格 合并哪几列
            int[] mergeColumnIndex = {3};
            // 需要从第几行开始合并
            int mergeRowIndex = 1;

            EasyExcel.write(response.getOutputStream(), ProductionInfo.class)
                    .autoCloseStream(Boolean.TRUE)
                    .registerWriteHandler(new ExcelFillCellMergeStrategy(mergeRowIndex, mergeColumnIndex))
                    .sheet("sheet" + i)
                    .doWrite(productionInfos);

        }


    }

    /**
     * 获取加工成品信息详细信息
     */
    @GetMapping(value = "/{productionId}")
    public AjaxResult getInfo(@PathVariable("productionId") Long productionId) {
        return success(productionInfoService.selectProductionInfoByProductionId(productionId));
    }

    /**
     * 新增加工成品信息
     */
    @PostMapping
    public AjaxResult add(@RequestBody ProductionInfo productionInfo) {
        String s = IdUtil.getSnowflake().nextIdStr();
        productionInfo.setProductionNum(s);
        return toAjax(productionInfoService.insertProductionInfo(productionInfo));
    }

    /**
     * 修改加工成品信息
     */
    @PutMapping
    public AjaxResult edit(@RequestBody ProductionInfo productionInfo) {
        return toAjax(productionInfoService.updateProductionInfo(productionInfo));
    }

    /**
     * 删除加工成品信息
     */
    @DeleteMapping("/{productionIds}")
    public AjaxResult remove(@PathVariable Long[] productionIds) {
        return toAjax(productionInfoService.deleteProductionInfoByProductionIds(productionIds));
    }

    /**
     * 导入信息
     */
    HashMap<String, Long> rawmap = new HashMap<>();
    HashMap<String, Long> dicmap = new HashMap<>();
    @RequestMapping("importData")
    public AjaxResult importData(MultipartFile file) throws IOException {

        getmap();
        List<ProductionInfo> list = EasyExcel.read(file.getInputStream())
                // 注册监听器，可以在这里校验字段
                .registerReadListener(new DailyImportListener())
                .head(ProductionInfo.class)
                .sheet()
                .headRowNumber(1)
                .doReadSync();

        for (ProductionInfo productionInfo : list) {
            String rawmaterialNum = productionInfo.getRawmaterialNum();
            Long aLong = rawmap.get(rawmaterialNum);
            productionInfo.setRawmaterialId(aLong);
            String standardName = productionInfo.getStandardName();
            Long aLong1 = dicmap.get(standardName);
            productionInfo.setStandardId(aLong1);
            System.err.println(productionInfo);

        }
        productionInfoService.insertProductionInfoBatch(list);

        return success("导入成功");



    }

    public void getmap(){


        List<RawmaterialInfo> numList = rawmaterialInfoService.getNumList();
        for (RawmaterialInfo rawmaterialInfo : numList) {
            Long rawmaterialNum = rawmaterialInfo.getRawmaterialNum();

            Long id = rawmaterialInfo.getId();
            rawmap.put(rawmaterialNum+"",id );
        }
        List<Dictionary> typelist = dictionaryService.getStandardListByType("standard_type");
        for (Dictionary dictionary : typelist) {
            String name = dictionary.getName();
            Long dictValue = dictionary.getDictValue();
            dicmap.put(name,dictValue);
        }

    }
}
